package com.deanlib.cabinet.utils;

import android.text.TextUtils;

import com.deanlib.cabinet.data.AppDatabase;
import com.deanlib.cabinet.data.model.Resource;
import com.deanlib.cabinet.ui.adapter.MediaGridAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Dean on 2023/2/18
 */
public class DataUtils {

    public static List<MediaGridAdapter.MediaGridData> createMediaGridData(List<Resource> resourceList){
        List<MediaGridAdapter.MediaGridData> mediaList = new ArrayList<>();
        int yearAdded = 0, monthAdded = 0;
        for (Resource resource : resourceList) {
            //先对数据进行有效性检查，并删除无效数据
            boolean validResource = false;

            if (!TextUtils.isEmpty(resource.path)) {
                validResource = true;
            } else if (!TextUtils.isEmpty(resource.localPath)) {
                //判断是否在同步目录中
                for (String dirPath : ConfigManager.getInstance().getSyncDirList()) {
                    if (resource.localPath.startsWith(dirPath)) {
                        validResource = true;
                        break;
                    }
                }
                if (!validResource) {
                    //判断本地是否存在
                    File file = new File(resource.localPath);
                    if (file.exists()) {
                        validResource = true;
                    }
                }
            }

            if (!validResource) {
                //无效的数据 数据库清除
                AppDatabase.getDaoSession().getResourceDao().deleteByKey(resource.md5);
                continue;
            }

            MediaGridAdapter.MediaGridData data = new MediaGridAdapter.MediaGridData();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(resource.resCreateTime * 1000);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            if (yearAdded != year || monthAdded != month) {
                MediaGridAdapter.MediaGridData titleData = new MediaGridAdapter.MediaGridData();
                titleData.setType(MediaGridAdapter.VIEW_TYPE_ITEM_TIME);
                titleData.setTitle(year + "-" + month);
                mediaList.add(titleData);
                yearAdded = year;
                monthAdded = month;
            }
            data.setData(resource);
            data.setType(MediaGridAdapter.VIEW_TYPE_ITEM_CONTENT);
            mediaList.add(data);
        }
        return mediaList;
    }
}
